<script setup lang="ts">
	import {onLoad} from '@dcloudio/uni-app';
	import {ref} from 'vue';
	import {useGetOrderEndTemplate} from '@/services/module/order/useOrder';

	const {endTemplate, getEndTemplate} = useGetOrderEndTemplate();

	defineOptions({
		name: 'OrderEndInfo',
	});

	const props = defineProps({
		orderDetail: {
			type: Object,
			required: true,
		},
		endStatus: {
			type: Boolean,
			required: true,
		},
	});

	// 工单id
	const orderId = ref('');

	// 视频预览弹出层显示状态
	const videoPreviewPopupInstance = ref();

	// 视频预览地址
	const videoPreviewUrl = ref('');

	/**
	 * 文件预览策略对象
	 */
	const filePreviewStrategy = {
		img: (field: Field, fileIndex: number) => {
			uni.previewImage({
				urls: field.value.map((file) => file),
				current: fileIndex,
			});
		},
		video: (field: Field, fileIndex: number) => {
			const file = field.value[fileIndex];
			if (file) {
				videoPreviewUrl.value = file;
				showVideoPreviewPopup();
			}
		},
	};

	/**
	 * 根据模板索引和字段索引寻找字段
	 * @param {number} templateIndex - 模板索引
	 * @param {number} fieldIndex - 字段索引
	 */
	const findFieldByTemplateIndexAndFieldIndex = (
		templateIndex: number,
		fieldIndex: number,
	) => {
		const template = endTemplate.value.objects[templateIndex];
		if (!template) {
			return false;
		}

		const field = template.content[fieldIndex];
		if (!field) {
			return false;
		}

		return field;
	};

	/**
	 * 文件预览事件
	 * @param {number} templateIndex - 模板索引
	 * @param {number} fieldIndex - 字段索引
	 * @param {number} fileIndex - 文件索引
	 */
	const handleFilePreview = (
		templateIndex: number,
		fieldIndex: number,
		fileIndex: number,
	) => {
		const field = findFieldByTemplateIndexAndFieldIndex(
			templateIndex,
			fieldIndex,
		);
		if (!field) {
			return false;
		}

		if (field.type === 5) {
			filePreviewStrategy['img'](field, fileIndex);
		}

		if (field.type === 7) {
			filePreviewStrategy['video'](field, fileIndex);
		}
	};

	/**
	 * 获取单选的值对应的文本
	 * @param {OrderEndTemplateContent} field - 字段对象
	 */
	const getSingleSelectText = (field: OrderEndTemplateContent) => {
		try {
			const option = JSON.parse(field.choices).find(
				(item) => item.id === field.value,
			);
			if (option) {
				return option.val;
			}
		} catch (error) {
			return '';
		}
	};

	/**
	 * 获取多选的值对应的文本
	 * @param {OrderEndTemplateContent} field - 字段对象
	 */
	const getMultipleSelectText = (field: OrderEndTemplateContent) => {
		try {
			const options = JSON.parse(field.choices);
			let values = JSON.parse(field.value);
			const result: Array<string> = [];
			values.forEach((item) => {
				const option = options.find((option) => option.id === item);
				if (option) {
					result.push(option.val);
				}
			});
			return result;
		} catch (error) {
			return [];
		}
	};

	/**
	 * 获取文件列表
	 * @param {OrderEndTemplateContent} field - 字段对象
	 */
	const getFileList = (field: OrderEndTemplateContent) => {
		try {
			return JSON.parse(field.value);
		} catch (error) {
			return [];
		}
	};

	/**
	 * 修改点击事件
	 */
	const onEdit = () => {
		const {id, departmentId, moduleId} = props.orderDetail;
		uni.navigateTo({
			url: `/pages_network/order/applyOrder?workId=${id}&departmentId=${departmentId}&moduleId=${moduleId}&status=${
				props.endStatus ? 1 : 2
			}`,
		});
	};

	/**
	 * 显示视频预览弹窗
	 */
	const showVideoPreviewPopup = () => {
		if (videoPreviewPopupInstance.value) {
			videoPreviewPopupInstance.value.open();
		}
	};

	/**
	 * 文件初始化
	 */
	const fileInit = () => {
		try {
			endTemplate.value.objects = endTemplate.value.objects.map((template) => {
				template.content = template.content.map((field) => {
					if ([5, 7].includes(field.type) && field.value) {
						field.value = JSON.parse(field.value);
					}
					return field;
				});
				return template;
			});
		} catch (error) {
			// error
		}
	};

	defineExpose({
		getEndTemplate: async (id: string) => {
			await getEndTemplate(id);
			fileInit();
		},
	});
</script>

<template>
	<view class="order-end-info">
		<view class="container">
			<view class="header">
				<uni-section
					title="结单信息"
					titleColor="#000"
					titleFontSize="28rpx"
					type="line"
				></uni-section>

				<view class="operate" @click="onEdit">修改</view>
			</view>

			<view class="template-list">
				<view
					class="template"
					v-for="(template, templateIndex) in endTemplate.objects"
					:key="templateIndex"
				>
					<view class="title">{{ template.templateName }}</view>
					<view class="field-list">
						<view
							class="field"
							v-for="(field, fieldIndex) in template.content"
							:key="fieldIndex"
						>
							<view class="label">{{ field.property }}：</view>
							<view class="value">
								<view v-if="[1, 2, 9, 10].includes(field.type)">
									{{ field.value }}
								</view>
								<view v-if="field.type === 3">
									{{ getSingleSelectText(field) }}
								</view>
								<view v-if="field.type === 4">
									{{ getMultipleSelectText(field).join('、') }}
								</view>
								<view v-if="[5, 7].includes(field.type)" class="img-list">
									<template
										v-for="(file, fileIndex) in field.value"
										:key="fileIndex"
									>
										<image
											:src="file"
											class="img"
											v-if="field.type === 5"
											@click="
												handleFilePreview(templateIndex, fieldIndex, fileIndex)
											"
										></image>
										<video
											:src="file"
											class="img"
											:show-center-play-btn="false"
											:show-play-btn="false"
											:controls="false"
											v-if="field.type === 7"
											@click="
												handleFilePreview(templateIndex, fieldIndex, fileIndex)
											"
										></video>
									</template>
								</view>
								<view v-if="field.type === 8" class="rate">
									<uni-rate
										disabled
										:model-value="Number(field.value) || 0"
									></uni-rate>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<uni-popup ref="videoPreviewPopupInstance">
			<view class="video-preview-container">
				<video :src="videoPreviewUrl"></video>
			</view>
		</uni-popup>
	</view>
</template>

<style scoped lang="scss">
	.order-end-info {
		margin: 0 24rpx;
		background-color: #fff;
		border-radius: 4rpx;

		.container {
			padding: 24rpx 0;

			.header {
				display: flex;
				font-size: 28rpx;
				justify-content: space-between;
				padding-right: 24rpx;

				.operate {
					color: #007cff;
				}
			}

			.template-list {
				padding: 0 24rpx;
				font-size: 26rpx;
				display: flex;
				flex-direction: column;
				row-gap: 32rpx;
				margin-top: 12rpx;

				.template {
					display: flex;
					flex-direction: column;
					row-gap: 12rpx;

					.title {
						font-weight: bold;
					}

					.field-list {
						display: flex;
						flex-direction: column;
						row-gap: 24rpx;

						.field {
							display: flex;

							.label {
								color: #777;
								white-space: nowrap;
								display: flex;
								align-items: center;
							}

							.value {
								.img-list {
									display: flex;
									flex-wrap: wrap;
									gap: 14rpx;

									.img {
										width: 80rpx;
										height: 80rpx;
										box-shadow: 0 0 2rpx 2rpx #e8e8e8;
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>
